package controller

import (
	"encoding/json"
	"game-server/database"
	"game-server/model"
	"net/http"

	"github.com/gin-gonic/gin"
)

type FormationController struct{}

func NewFormationController() *FormationController {
	return &FormationController{}
}

// GetFormation 获取玩家当前布阵
func (c *FormationController) GetFormation(ctx *gin.Context) {
	userID := ctx.GetUint("userID")

	var formation model.Formation
	result := database.DB.Where("user_id = ?", userID).First(&formation)
	if result.Error != nil {
		// 如果没有布阵记录，返回空布阵
		ctx.JSON(http.StatusOK, gin.H{
			"id":        0,
			"user_id":   userID,
			"positions": []uint{0, 0, 0, 0},
		})
		return
	}

	// 解析存储的JSON数据
	var positions []uint
	if err := json.Unmarshal(formation.Positions, &positions); err != nil {
		positions = make([]uint, 4)
	}

	// 返回解析后的数据
	ctx.JSON(http.StatusOK, gin.H{
		"id":        formation.ID,
		"user_id":   formation.UserID,
		"positions": positions,
	})
}

// SaveFormation 保存布阵
func (c *FormationController) SaveFormation(ctx *gin.Context) {
	userID := ctx.GetUint("userID")

	var input struct {
		Positions []uint `json:"positions" binding:"required,len=4"`
	}

	if err := ctx.ShouldBindJSON(&input); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "无效的布阵数据"})
		return
	}

	// 验证英雄是否属于该玩家
	for _, heroID := range input.Positions {
		if heroID != 0 {
			var count int64
			database.DB.Model(&model.UserHero{}).Where("user_id = ? AND hero_id = ?", userID, heroID).Count(&count)
			if count == 0 {
				ctx.JSON(http.StatusBadRequest, gin.H{"error": "存在未拥有的英雄"})
				return
			}
		}
	}

	// 将数组转换为JSON字符串
	positionsJSON, err := json.Marshal(input.Positions)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "数据处理错误"})
		return
	}

	// 更新或创建布阵
	var formation model.Formation
	result := database.DB.Where("user_id = ?", userID).First(&formation)
	if result.Error != nil {
		// 创建新布阵
		formation = model.Formation{
			UserID:    userID,
			Positions: positionsJSON, // 使用JSON字符串
		}
		database.DB.Create(&formation)
	} else {
		// 更新现有布阵
		formation.Positions = positionsJSON // 使用JSON字符串
		database.DB.Save(&formation)
	}

	ctx.JSON(http.StatusOK, formation)
}

// GetOwnedHeroes 获取玩家拥有的英雄
func (c *FormationController) GetOwnedHeroes(ctx *gin.Context) {
	userID := ctx.GetUint("userID")

	var userHeroes []model.UserHero
	database.DB.Where("user_id = ?", userID).Find(&userHeroes)

	var heroes []model.Hero
	for _, uh := range userHeroes {
		var hero model.Hero
		database.DB.Preload("Skills").First(&hero, uh.HeroID)
		heroes = append(heroes, hero)
	}

	ctx.JSON(http.StatusOK, heroes)
}
